
<!DOCTYPE html>
<html>
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./css/w3.css">
<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>

<link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-blue-grey.css">
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.staticfile.org/validator/10.11.0/validator.min.js"></script>
<style>
html, body, h1, h2, h3, h4, h5 {font-family: "Open Sans", sans-serif}
</style>

<body class="w3-theme-l5">
  <div id="id01" class="w3-modal">
    <div class="w3-modal-content w3-card-4 w3-animate-zoom" style="max-width:300px">

      <div class="w3-center"><br>
        <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-xlarge w3-hover-red w3-display-topright" title="Close Modal">&times;</span>
        <img src="img_avatar4.png" alt="Avatar" style="width:30%" class="w3-circle w3-margin-top">
      </div>

        <div class="w3-container">
          <label><b>店铺名称</b></label>
          <input class="w3-input w3-border w3-margin-bottom" type="text" placeholder="Enter Username" id="groupname" required>
          <label><b>地址</b></label>
          <input class="w3-input w3-border" type="text" placeholder="" id="groupaddr" required>
		  <label><b>联系电话</b></label>
          <input class="w3-input w3-border" type="text" placeholder="" id="groupphone" required>
          <button class="w3-button w3-block w3-green w3-section w3-padding" id="addGroupBtn" onclick="addGroup(this)">添加</button>
          
        </div>
      

      <div class="w3-container w3-border-top w3-padding-16 w3-light-grey">
        <button onclick="document.getElementById('id01').style.display='none'" type="button" class="w3-button w3-red">取消</button>
      </div>

    </div>
  </div>
<!-- Navbar -->
<div class="w3-top">
 <div class="w3-bar w3-theme-d2 w3-left-align w3-large">
  <a class="w3-bar-item w3-button w3-hide-medium w3-hide-large w3-right w3-padding-large w3-hover-white w3-large w3-theme-d2" href="javascript:void(0);" onclick="openNav()"><i class="fa fa-bars"></i></a>
  <a href="#" class="w3-bar-item w3-button w3-padding-large w3-theme-d4"><i class="fa fa-home w3-margin-right"></i>gukedi</a>
  <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white" title="News">News</a>
  <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white" title="Account Settings">Introduction</a>
  <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white" title="Messages">Download</a>

  <a href="#" class="w3-bar-item w3-button w3-hide-small w3-right w3-padding-large w3-hover-white" title="My Account">
    My Account
  </a>
 </div>
</div>

<!-- Navbar on small screens -->
<div id="navDemo" class="w3-bar-block w3-theme-d2 w3-hide w3-hide-large w3-hide-medium w3-large">
  <a href="#" class="w3-bar-item w3-button w3-padding-large">Link 1</a>
  <a href="#" class="w3-bar-item w3-button w3-padding-large">Link 2</a>
  <a href="#" class="w3-bar-item w3-button w3-padding-large">Link 3</a>
  <a href="#" class="w3-bar-item w3-button w3-padding-large">My Profile</a>
</div>

<!-- Page Container -->
<div class="w3-container w3-content" style="max-width:1400px;margin-top:80px">    
  <!-- The Grid -->
  <div class="w3-row">
    <!-- Left Column -->
    <div class="w3-col m3">
      <!-- Profile -->
      <div id="myprofile" class="w3-card w3-round w3-white">
        <div class="w3-container">
         <h4 class="w3-center">My Profile</h4>
         <p class="w3-center"><img src="/w3images/avatar3.png" class="w3-circle" style="height:106px;width:106px" alt="Avatar"></p>
         <hr>
         <p><i class="fa fa-pencil fa-fw w3-margin-right w3-text-theme"></i> Designer, UI</p>
         <p><i class="fa fa-home fa-fw w3-margin-right w3-text-theme"></i> London, UK</p>
         <p><i class="fa fa-birthday-cake fa-fw w3-margin-right w3-text-theme"></i> April 1, 1988</p>
        </div>
      </div>
      <br>
      
       <div class="w3-bar-block w3-card">
  
  <!-- <a href="usermain.html?type=myfeeds" id="myfeedssidelink"  class="w3-bar-item w3-button tablink">我的动态</a> -->
  <a onclick=showGroupUI(true) class="w3-bar-item w3-button w3-green tablink">新建店铺</a>
  
        </div>


    
    <!-- End Left Column -->
    </div>
    
    <!-- Middle Column -->
    <div class="w3-col m7">
    
      <div id="tabbars"  class="w3-bar">
    <!--  <button class="w3-bar-item w3-button tablink w3-red" onclick="openTabs(event,'myfeeds')">我的动态</button>  -->
    <button class="w3-bar-item w3-button tablink w3-red" onclick="openTabs(event,'mygroups')">我的店铺</button>
    <button class="w3-bar-item w3-button tablink" onclick="openTabs(event,'mycards')">我的会员卡</button>
      </div>
      <!--
      <div id="myfeeds" class="w3-container w3-border tab">
      <div class="w3-container w3-card w3-white w3-round w3-margin"><br>
        <img src="/w3images/avatar2.png" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px">
        <span class="w3-right w3-opacity">1 min</span>
        <h4>John Doe</h4><br>
        <hr class="w3-clear">
        <p>申请加入会员，是否同意？</p>

        <button type="button" class="w3-button w3-theme-d1 w3-margin-bottom"><i class="fa fa-thumbs-up"></i> &nbsp;Like</button> 
        <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom"><i class="fa fa-comment"></i> &nbsp;Comment</button> 
      </div>
      </div>
        -->
      <div id="mygroups" class="w3-container w3-border tab">
         <div class="w3-container w3-card w3-round w3-margin">

        <header class="w3-container w3-light-grey">
          <h3>正在读取店铺信息</h3>
        </header>

 
        <button class="w3-button w3-block w3-green">Manage</button>

        </div> 
      </div>

      <div id="mycards" class="w3-container w3-border tab" style="display:none">
         <div class="w3-container w3-card w3-round w3-margin">

        <header class="w3-container w3-light-grey">
          <h3>正在读取会员卡信息</h3>
        </header>



        <button class="w3-button w3-block w3-green">查看</button>

        </div> 
      </div>

      
      
    <!-- End Middle Column -->
    </div>
    
    <!-- Right Column -->
    <div class="w3-col m2">
      <div class="w3-card w3-round w3-white w3-center">
	    <h4 class="w3-blue"> 操作事件 </h4>
        <div id="requestResult" class="w3-container" style="height: 600px;overflow: auto;">
		
        </div>
      </div>
      <br>
      
      
      <br>
      <!--
      <div class="w3-card w3-round w3-white w3-padding-32 w3-center">
        <p><i class="fa fa-bug w3-xxlarge"></i></p>
      </div>
      -->
    <!-- End Right Column -->
    </div>
    
  <!-- End Grid -->
  </div>
  
<!-- End Page Container -->
</div>
<br>

<!-- Footer -->
<footer class="w3-container w3-theme-d3 w3-padding-16">
  <h5>Footer</h5>
</footer>


<script src="./js/table.js"></script>
<script>
// Accordion
function myFunction(id) {
  var x = document.getElementById(id);
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
    x.previousElementSibling.className += " w3-theme-d1";
  } else { 
    x.className = x.className.replace("w3-show", "");
    x.previousElementSibling.className = 
    x.previousElementSibling.className.replace(" w3-theme-d1", "");
  }
}

// Used to toggle the menu on smaller screens when clicking on the menu button
function openNav() {
  var x = document.getElementById("navDemo");
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else { 
    x.className = x.className.replace(" w3-show", "");
  }
}

initialize('hqD9IMTNsFSk2LxbiFnBEvCp-gzGzoHsz','ITs4Ni1EiEI5sEcQQ4CBJqpb');
const GROUPS="groups";
const GROUPMEMBERS="groupmembers";
const GROUPMSG="groupmsg";
const MEMBERMSG="membermsg";
var g_groups={};

if(!currentUser())
{
   window.location.href="login.html";
}
else

{
	showMyProfile(currentUser());
	var onGetGroupSuccess = function(tablename, tobj)
    {
       updateGrpInfo(tobj);
	   
    }
    var onUpdateSuccess = function(tablename, tobj)
    {
    console.log("object updated on " + tablename + " with objectId: " + tobj.id );
    }


	var onErrorAll = function(tablename, tobj, error)
	{
	console.error("Failed to create " + tablename + " with data:" + tobj +  " with error message: " + error.message);
	}
    
	var onQueryResult=function(tablename, results)
	{
	   console.log(tablename);
	   console.log(results);
       if(tablename === GROUPS)
            {
          
            showAllGroupsInHeader(results);
            //findItemsEqualTo(GROUPMEMBERS, "mid", currentUser().id, onQueryResult);
            //find all members ship
			

            for(var i=0;i<results.length;i++)
            {
                let rid=findItemsEqualTo(GROUPMSG, 'grpid', results[i].id, onQueryResult);
				//appendRequest(rid,"处理店铺消息"+(i+1));
            }
            }

       else if(tablename == GROUPMSG)
            {
              for(var i=0;i<results.length;i++)
              {
                 if(Number(results[i].get('answer')) == 1 && results[i].get('cardid'))
                 {
                    updateTableItem(GROUPMEMBERS, results[i].get('cardid'), {'mid':results[i].get('frommid')}, onUpdateSuccess, onErrorAll);
                    results[i].set('answer', "2");
                    results[i].save().then(function(obj){console.log("update answer success")}, function(error){"update answer eror:"+error.message;});
                 }
              }
            }
        
	}
	console.log(AV.User.current());
    //find all groups
	var rid = findItemsEqualTo(GROUPS, "ownerid", currentUser().id, onQueryResult);
    appendRequest(rid, "更新店铺信息");
	if(currentUser().getMobilePhoneNumber())
	{	
	rid= findItemsEqualTo(GROUPMSG, "phone",currentUser().getMobilePhoneNumber(), function(tablename, results)
    {
        showAllMemberCards(results);
    });
	appendRequest(rid,"更新会员卡信息");
	}
    
	//var rid = createTableItem(GROUPS, {"ownerid":currentUser().id, "grpname":"group3", "grpaddr":"shanghai", "phone":"18939895003"}, onCreateSuccess, onError);
	//console.log(getRequestData(rid));
	//var rid2 = createTableItem(GROUPS, {"ownerid":currentUser().id, "grpname":"group4", "grpaddr":"shanghai", "phone":"18018661248"}, onCreateSuccess, onError);
	//console.log(getRequestData(rid2));
    

    
}

function addGroup(e)
{
	var onCreateSuccess = function(tablename, tobj)
	{
        console.log("New object created on " + tablename + " with objectId: " + tobj.id );
		
        if(tablename === GROUPS)
        {
		   showGroupUI(false);
		   	let rid = findItemsEqualTo(GROUPS, "ownerid", currentUser().id, onQueryResult);
			appendRequest(rid, "更新店铺信息");
           //create a msg for user to confirm;
        }
        else if(tablename === GROUPMSG)
        {
            
        }
        

	}
   if(e)
   {
   e.innerText="正在添加...";
   e.disabled = true;
   }
   addNewGroup(ele("groupname").value, ele("groupaddr").value, ele("groupphone").value,  onCreateSuccess, onErrorAll);
}
function addMemberToGroup(mphone, memail, jifen,grpid, onSuccess, onError)
{
return createTableItem(GROUPMEMBERS, {"grpid":grpid, "mphone":mphone, "memail":memail,"jifen":jifen,"mid":""},onSuccess, onError,[currentUser.id]);
}
function showMyProfile(obj)
{
    	var dd = ele("myprofile");
		var html ="";
        html += '<div class="w3-container"><h2>';
        html += obj.getUsername();
        html += '</h2><p>';
        html += obj.getEmail();
        html += '</p><p>';
        html += obj.getMobilePhoneNumber();
        html += '</p></div>';
		
		dd.innerHTML = html;
}
function showGroupUI(show)
{
//show a form ui.
if(show)
	document.getElementById('id01').style.display='block';
else
    {
    ele('addGroupBtn').innerText='确定';
    ele('addGroupBtn').disabled=false;
    
    document.getElementById('id01').style.display='none';
    }
}
function addNewGroup(name, addr, phone,onSuccess, onError)
{
    var rid = createTableItem(GROUPS, {"ownerid":currentUser().id, "grpname":name, "grpaddr":addr, "phone":phone}, onSuccess, onError,[currentUser().id]);
	appendRequest(rid,"新建店铺");
	return rid;
}
function onManageGroup(grpid)
{
console.log(grpid);

//addMemberToGroup("18939895003", "sdf@123.com", 100, grpid, onCreateSuccess, onError);
 //findItemsEqualTo(GROUPMEMBERS, "grpid", grpid, onQueryResult);
 window.location.href="groupmain.html?grpid="+grpid;
}
function onConfirmMember(e, grpmsgid)
{
    var onConfirmError = function(tablename, tobj, error)
    {
        console.error("Failed to create " + tablename + " with data:" + tobj +  " with error message: " + error.message);
        e.innerText="确认";
        e.disable = false;
    }
    console.log(this == e);
    e.innerText="已确认";
    e.disable = true;
   let rid= updateTableItem(GROUPMSG, grpmsgid, {'answer':"1", "frommid":currentUser().id}, onUpdateSuccess, onConfirmError);
   appendRequest(rid,"确认会员卡");
}
function removeGroup(gid)
{
    var r = confirm("Remove group will result in removing all members ? ")
    if(r)
    {    
    let rid=removeTableItem(GROUPS, gid, 
                            function(suc)
                            {
                            console.log("removed group"+gid);
                            let rid2 = findItemsEqualTo(GROUPMEMBERS, 'grpid', gid, 
                                function(tablename, results)
                                {
                                   if(results.length > 0)
                                   {
                                        AV.Object.destroyAll(results).then(
                                        function(objects)
                                        {
                                           updateRequest(rid2, 1);
                                        }, 
                                        function(error)
                                        {
                                           updateRequest(rid2, "删除出错"+error.message);
                                        });
                                   }
                                }
                                ,
                                function(tablename, error)
                                {
                                     updateRequest(rid2, error.message);
                                }
                            )
                            appendRequest(rid2, "删除会员信息");
                            let rid3 = findItemsEqualTo(GROUPS, "ownerid", currentUser().id, onQueryResult);
                            appendRequest(rid3, "更新店铺信息");
                            
                            },
                            function(err)
                            {
                            updateRequest(rid,error.message);
                            console.log("error remove group"+gid);
                            }
                            );
                            
    appendRequest(rid,"删除店铺");
    }
}
function createGroup(name, address,phone)
{

}
function updateGrpInfo(grpobj)
{
   if(grpobj && ele(grpobj.id))
   {
        let html = '<header class="w3-container"><h3>';
        html += grpobj.get("grpname");
        html += '</h3></header><div class="w3-container"><p>';
        html += grpobj.get("grpaddr");
        html += '</p><p>';
        html += grpobj.get("phone");
		html += "</p></div>";
		ele(grpobj.id).innerHTML = html;
	}
}
function showAllMemberCards(results)
{
	if(results.length == 0)
	{
	   	var dd = ele("mycards");
		var html ="";
        html += '<div class="w3-container w3-card w3-round w3-margin">';
        html += '<h1>您还没有任何会员卡。</h1></div>';        
        dd.innerHTML = html;
	}
	else
	{
    	var dd = ele("mycards");
		var html ="";
		for(var i=0;i<results.length;i++)
		{
		
 
        html += '<div class="w3-container w3-card w3-round w3-margin"><div class="w3-container" id=';
		html += results[i].get("grpid");
        html += "></div>";

        html += '<div class="w3-blue"><p>会员卡号:';
        html += results[i].get("cardid");
        html += '</p></div><button onclick=onCheckMembership("';
        html += results[i].get("cardid");
   
        html += '") class="w3-button w3-green">查看</button>';
        var mid = results[i].get('answer');
        if(Number(mid) == 0)
            {
            //confirm will send your id to groups;
            html += '<button onclick=onConfirmMember(this,"';
            html += results[i].id;
            html += '") class="w3-button w3-blue">确认</button>';
            }
            html += '</div>';
		}
		dd.innerHTML = html;
		for(var i=0;i<results.length;i++)
		{
		findItemById(GROUPS, results[i].get("grpid"), onGetGroupSuccess,onError);
		}
	}
}
function showAllGroupsInHeader(results)
{
	if(results.length == 0)
	{
	   	var dd = ele("mygroups");
		var html ="";
        html += '<div class="w3-container w3-card w3-round w3-margin"><h3>快来创建店铺吧！</h3>';
        html += '<button onclick=showGroupUI(true) class="w3-button w3-block w3-green">新建店铺</button></div>';        
        dd.innerHTML = html;
	}
	else
	{    
		var dd = ele("mygroups");
		var html ="";
		for(var i=0;i<results.length;i++)
		{
        //g_groups[results[i].id]=results[i];
        html += '<div class="w3-container w3-card w3-round w3-margin">'

        html += '<header class="w3-container"><h3>';
        html += results[i].get("grpname");
        html += '</h3></header><div class="w3-container"><p>';
        html += results[i].get("grpaddr");
        html += '</p><p>';
        html += results[i].get("phone");
        html += '</p><p>新会员请求:<a href="#">';
        html += 2;
        html += '</a></p><hr></div><button onclick=onManageGroup("';
        html += results[i].id;
        html += '") class="w3-button w3-green">管理</button><button onclick=removeGroup("';
        html += results[i].id;
        html += '") class="w3-right w3-red w3-button">删除</button></div>';
		}
		dd.innerHTML = html;
	}
}
function showGroupProfile()
{

}


function clickGroupDropdown() {
  var x = document.getElementById("groupdropdown");
  if (x.className.indexOf("w3-show") == -1) {  
    x.className += " w3-show";
  } else { 
    x.className = x.className.replace(" w3-show", "");
  }
}

function openTabs(evt, tabName) {
  var i, x, tablinks;
  x = document.getElementsByClassName("tab");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablink");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" w3-red", "");
  }
  document.getElementById(tabName).style.display = "block";
  evt.currentTarget.className += " w3-red";
}
</script>

</body>
</html> 
